package com.leslie.hhcommunity.service.impl;

import com.leslie.hhcommunity.dao.UserMapper;
import com.leslie.hhcommunity.entity.LoginTicket;
import com.leslie.hhcommunity.entity.User;
import com.leslie.hhcommunity.service.UserService;
import com.leslie.hhcommunity.util.CommunityConstant;
import com.leslie.hhcommunity.util.CommunityUtil;
import com.leslie.hhcommunity.util.MailClient;
import com.leslie.hhcommunity.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.service.impl
 * @ClassnName:UserServiceImpl
 * @Description:
 * @Date 2021/12/31  17:33
 */
@Service
public class UserServiceImpl implements UserService, CommunityConstant {

	@Autowired
	UserMapper userMapper;
	//	@Autowired
//	LoginTicketMapper loginTicketMapper;
	@Autowired
	RedisTemplate redisTemplate;

	@Value("${community.path.domain}")
	private String domain;

	@Value("${server.servlet.context-path}")
	private String contextPath;

	@Autowired
	private TemplateEngine templateEngine;
	@Autowired
	MailClient mailClient;

	/**
	 * 根据id查询用户
	 *
	 * @param id
	 * @return
	 */
	@Override
	public User findUserById(int id) {
//		return userMapper.selectById(id);
		User user = getCache(id);
		if (user == null) {
			user = initCache(id);
		}
		return user;
	}

	/**
	 * 注册
	 *
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> register(User user) {
		Map<String, Object> map = new HashMap<>();
		//空值处理
		if (user == null) {
			throw new IllegalArgumentException("参数不能位空!");
		}

		if (StringUtils.isBlank(user.getUsername())) {
			map.put("usernameMsg", "账户不能为空");
			return map;
		}

		if (StringUtils.isBlank(user.getPassword())) {
			map.put("passwordMsg", "密码不能为空");
			return map;
		}

		if (StringUtils.isBlank(user.getEmail())) {
			map.put("emailMsg", "邮箱不能为空");
			return map;
		}

		//验证账号
		User u1 = userMapper.selectByName(user.getUsername());
		if (u1 != null) {
			map.put("usernameMsg", "该账号已存在");
			return map;
		}
		//验证邮箱
		User u2 = userMapper.selectByEmail(user.getEmail());
		if (u2 != null) {
			map.put("emailMsg", "该邮箱已被注册");
			return map;
		}

		//注册用户
		user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
		user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
		//普通用户
		user.setType(0);
		//0未激活
		user.setStatus(0);
		user.setActivationCode(CommunityUtil.generateUUID());
		user.setHeaderUrl(
				//new Random().nextInt(1000)替换这个动态的 %d
				String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
		user.setCreateTime(new Date());
		userMapper.insertUser(user);

		//激活邮件
		Context context = new Context();
		context.setVariable("email", user.getEmail());
		// http://localhost:8080/community/activation/101/code
		String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
		context.setVariable("url", url);
		//加载到/mail/activation
		String content = templateEngine.process("/mail/activation", context);
		mailClient.sendMail(user.getEmail(), "激活邮件", content);
		return map;
	}

	/**
	 * 激活
	 *
	 * @param userId
	 * @param code
	 * @return
	 */
	@Override
	public int activation(int userId, String code) {
		User user = userMapper.selectById(userId);
		if (user.getStatus() == 1) {
			return ACTIVATION_REPEAT;
		} else if (user.getActivationCode().equals(code)) {
			userMapper.updateStatus(userId, 1);
			//这里采用更新操作之后清空缓存
			clearCache(userId);
			return ACTIVATION_SUCCESS;
		} else {
			return ACTIVATION_FAILED;
		}
	}

	/**
	 * 登录
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @param expired  凭证过期时间
	 * @return
	 */
	@Override
	public Map<String, Object> login(String username, String password, int expired) {
		Map<String, Object> map = new HashMap<>();
		//空值处理
		if (StringUtils.isBlank(username)) {
			map.put("usernameMsg", "账号不能为空");
			return map;
		}
		if (StringUtils.isBlank(password)) {
			map.put("passwordMsg", "密码不能为空");
			return map;
		}

		//验证账号
		User user = userMapper.selectByName(username);
		if (user == null) {
			map.put("usernameMsg", "该账号不存在");
			return map;
		}
		//验证状态
		if (user.getStatus() == 0) {
			map.put("usernameMsg", "该账号未激活");
			return map;
		}
		//验证密码
		password = CommunityUtil.md5(password + user.getSalt());
		if (!user.getPassword().equals(password)) {
			map.put("passwordMsg", "密码错误");
			return map;
		}

		//生成登录凭证
		LoginTicket loginTicket = new LoginTicket();
		loginTicket.setUserId(user.getId());
		loginTicket.setTicket(CommunityUtil.generateUUID());
		//0表示登录状态
		loginTicket.setStatus(0);
		loginTicket.setExpired(new Date(System.currentTimeMillis() + expired * 1000));
//		loginTicketMapper.insertLoginTicket(loginTicket);

		String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
		// redisTemplate 将 loginTicket会序列化成json
		redisTemplate.opsForValue().set(redisKey, loginTicket);

		map.put("ticket", loginTicket.getTicket());
		return map;
	}

	@Override
	public void logout(String ticket) {
//		loginTicketMapper.updateStatus(ticket, 1);
		String redisKey = RedisKeyUtil.getTicketKey(ticket);
		LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
		loginTicket.setStatus(1);
		redisTemplate.opsForValue().set(redisKey, loginTicket);
	}

	/**
	 * 根据ticket查询LoginTicket对象
	 *
	 * @param ticket
	 * @return
	 */
	@Override
	public LoginTicket findLoginTicket(String ticket) {
//		return loginTicketMapper.selectByTicket(ticket);
		String redisKey = RedisKeyUtil.getTicketKey(ticket);
		return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
	}

	/**
	 * 更新头像
	 *
	 * @param userId
	 * @param headerUrl
	 * @return
	 */
	@Override
	public int updateHeader(int userId, String headerUrl) {
		int rows = userMapper.updateHeader(userId, headerUrl);
		clearCache(userId);
		//清空之后初始化
		initCache(userId);
		return rows;
	}

	/**
	 * 通过用户名查找用户
	 *
	 * @param username
	 * @return
	 */
	@Override
	public User selectByName(String username) {
		return userMapper.selectByName(username);
	}

	//优先冲缓存中取值
	private User getCache(int userId) {
		String redisKey = RedisKeyUtil.getUserKey(userId);
		return (User) redisTemplate.opsForValue().get(redisKey);
	}

	//取不到时初始化缓存
	private User initCache(int userId) {
		User user = userMapper.selectById(userId);
		String redisKey = RedisKeyUtil.getUserKey(userId);
		redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
		return user;
	}

	//清除缓存
	private void clearCache(int userId) {
		String redisKey = RedisKeyUtil.getUserKey(userId);
		redisTemplate.delete(redisKey);
	}

	/**
	 * 获取用户权限
	 *
	 * @param userId
	 * @return
	 */
	public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
		User user = this.findUserById(userId);

		List<GrantedAuthority> list = new ArrayList<>();
		list.add(new GrantedAuthority() {

			@Override
			public String getAuthority() {
				switch (user.getType()) {
					case 1:
						return AUTHORITY_ADMIN;
					case 2:
						return AUTHORITY_MODERATOR;
					default:
						return AUTHORITY_USER;
				}
			}
		});
		return list;
	}
}
